package com.eol.admin.modules.system.rest;

import com.eol.admin.modules.logging.log.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.eol.admin.common.utils.SecurityUtils;
import com.eol.common.base.BaseResponse;
import com.eol.common.base.BaseResponseCode;
import com.eol.common.constants.BaseCommonConstants;
import com.eol.common.exception.BaseException;
import com.eol.common.mail.MailServiceImpl;
import com.eol.common.utils.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2019/12/3
 * Time: 3:14 PM
 * Description: CodeController
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
public class CodeController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private MailServiceImpl mailService;

    @Log("获取邮箱验证码")
    @ApiOperation("获取邮箱验证码")
    @RequestMapping(value = "getEmailCode", method = RequestMethod.GET)
    public BaseResponse resetCode(@RequestParam("email") String email) {
        if (!StringUtils.isEmail(email)) {
            throw new BaseException("邮箱格式错误");
        }
        UserDetails userDetails = SecurityUtils.getUserDetails();
        String code = String.valueOf((int) ((Math.random() * 6 + 1) * 100000));
        mailService.sendSimpleMail(email, "重置邮箱验证码", code);
        redisTemplate.opsForValue().set(BaseCommonConstants.RESET_EMAIL + userDetails.getUsername(), code, 15, TimeUnit.MINUTES);
        return new BaseResponse(BaseResponseCode.OK);
    }
}
